package com.lst.servlet;

import java.awt.image.BufferedImage;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.druid.util.StringUtils;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.lst.base.entity.BaseRequest;
import com.lst.base.entity.BaseResponse;
import com.lst.common.CommCode;
import com.lst.entity.request.QuestionReqPara;
import com.lst.entity.response.QuestionResPara;
import com.lst.model.Answer;
import com.lst.model.Question;
import com.lst.service.AnswerService;
import com.lst.service.ClientNumService;
import com.lst.service.QuestionService;
import com.lst.utils.DateUtil;
import com.lst.utils.RequestUtils;


/**
 * @ClassName: QuestionDetailServlet
 * @Description: 问题详情接口
 * 
 */
public class QuestionDetailServlet extends BaseServlet {

	/**
	 * @Fields serialVersionUID
	 */
	private static final long serialVersionUID = 1L;

	private QuestionService questionService = ctx.getBean(QuestionService.class);
	
	private ClientNumService clientNumService = ctx.getBean(ClientNumService.class);
	
	private AnswerService answerService = ctx.getBean(AnswerService.class);
	
	@Override
	public void doGet(HttpServletRequest request, HttpServletResponse response) {
		doPost(request, response);
	}

	@Override
	public void doPost(HttpServletRequest request, HttpServletResponse response) {
		Date startDate = new Date();
		logger.info("doPost begin: " + startDate);
		QuestionResPara resPara = new QuestionResPara();

		try {
			QuestionReqPara reqPara = getReqPara(request);
		
		if(isCheckField(reqPara,resPara)){
		    Integer userid = Integer.valueOf(reqPara.getUserid());
			Integer questionId = Integer.valueOf(reqPara.getQuestionId());					
			
			Question question=questionService.selectByPrimaryKey(questionId);
			if(question!=null){
				//转换时间格式
				Date date=question.getCreateDate();
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				String str=sdf.format(date);
				question.setCreateDate2(DateUtil.changeTime(str));
				
				//计算图片宽高
				if (question.getPictureUrl() != null && question.getPictureUrl() != "") {
						String[] strs = question.getPictureUrl().split(",");
						int[] widths = new int[strs.length];
						int[] heights = new int[strs.length];

						for (int i = 0; i < strs.length; i++) {
							InputStream is = null;
							BufferedImage src = null;
							try {
								is = new FileInputStream(CommCode.readUrl + strs[i].substring(13));
								src = javax.imageio.ImageIO.read(is);
								widths[i] = src.getWidth(); // 得到源图宽
								heights[i] = src.getHeight(); // 得到源图高
								is.close();
							} catch (Exception e) {
								e.printStackTrace();
							}
						}
						question.setWidths(widths);
						question.setHeights(heights);
					}
				
				  //标识是否收藏
				Map<String, Object> fmap = new HashMap<String, Object>();
				fmap.put("enabled", true);
				fmap.put("isdeleted", false);
				fmap.put("clientid", userid);
				fmap.put("actid", question.getQuestionId());
				fmap.put("acttype", CommCode.SYSTEM_CARESEL_RANGE_QUESTION);
				fmap.put("numtype", CommCode.SYSTEM_COUNT_FAVORITE);
				Integer count = clientNumService.queryCountByMap(fmap);
				if(count>0){
					question.setIsFavorite(true);
				}else{
					question.setIsFavorite(false);
				}
				
				//标识是否回答过问题
				Map<String,Object> map=new HashMap<String,Object>();
				map.put("answerSourceId", questionId);
				map.put("answerCreateUser", userid);
				Answer answer=answerService.selectByMap(map);
				if(answer!=null){
					question.setIsAnswer(true);
				}else{
					question.setIsAnswer(false);
				}
				
				resPara.setQuestion(question);
				resPara.setCode(CommCode.M_Y000000);
				resPara.setMessage(CommCode.M_Y000001);
			}else{
				resPara.setCode(CommCode.M_A000001);
            	resPara.setMessage(CommCode.M_A000002);
			}
			
			
		  }
		} catch (Exception e) {
			resPara.setCode(CommCode.M_A000000);
			resPara.setMessage(CommCode.M_SYS0001);

			logger.error("doPost error: ", e);
		}
		
		try {
			response.setContentType("application/json;charset=utf-8");
			response.setHeader("pragma", "no-cache");
			response.setHeader("cache-control", "no-cache");

			Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").excludeFieldsWithoutExposeAnnotation().serializeNulls().create();
			String jsonResult = gson.toJson(resPara);
			logger.info("QuestionDetailServlet jsonResult:" + jsonResult);

			PrintWriter out = response.getWriter();
			out.print(jsonResult);
			out.flush();
			out.close();

			logger.info("doPost end run(s): " + DateUtil.calLastedTime(startDate));
		} catch (Exception e) {
			resPara.setCode(CommCode.M_A000000);
			resPara.setMessage(CommCode.M_SYS0003);

			logger.error("doPost error: ", e);
		}
	}

	@Override
	public QuestionReqPara getReqPara(HttpServletRequest request) {

		QuestionReqPara reqPara = null;

		try {
			BaseRequest baseRequest = RequestUtils.getRequestPara(request, new QuestionReqPara());

			reqPara = (QuestionReqPara) baseRequest.clone();

			String userid = request.getParameter("userid");
			String questionId = request.getParameter("questionId");
			
			logger.info("reqPara userid:" + userid);
			logger.info("reqPara questionId: " + questionId);
		

	        reqPara.setQuestionId(questionId);
	        reqPara.setUserid(userid);

		} catch (Exception e) {
			logger.error("getReqPara error: ", e);
		}

		return reqPara;
	}

	@Override
	public boolean isCheckField(BaseRequest reqPara, BaseResponse resPara) {
		boolean flag = false;

		QuestionReqPara cdReqPara = (QuestionReqPara) reqPara;
		BaseResponse cdResPara = (BaseResponse) resPara;

		if (StringUtils.isEmpty(cdReqPara.getQuestionId())) {
			cdResPara.setCode(CommCode.M_A000000);
			cdResPara.setMessage("问题id为空");
		}else if (StringUtils.isEmpty(cdReqPara.getUserid())) {
			cdResPara.setCode(CommCode.M_A000000);
			cdResPara.setMessage(CommCode.M_P000002);
		} else {
			flag = true;
		}

		return  flag;
	}

}
